package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.itheima.dao.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements  OrderSettingService {

    @Autowired
    OrderSettingMapper orderSettingMapper;

    @Override
    public void setNumberByDate(OrderSetting orderSetting) {
           //根据日期查询是否存在预约设置
        Integer count = orderSettingMapper.findCountByDate(orderSetting.getOrderDate());
        if(null != count && count > 0){
            //存在就更新
            orderSettingMapper.edit(orderSetting);
        } else {
            //不存在就插入
            orderSettingMapper.add(orderSetting);
        }

    }

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    // 1024 + 996 = 2020
    // 1024 + 007 = 1031
    @Override
    public void batchSave(List<OrderSetting> params) {
        for (OrderSetting param : params) {
            setNumberByDate(param);
        }
        //多线程

        List<List<OrderSetting>> partition = Lists.partition(params, 40);
        for (List<OrderSetting> orderSettings : partition) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    for (OrderSetting orderSetting : orderSettings) {
                        setNumberByDate(orderSetting);
                    }
                }
            });
        }

    }

    @Override
    public List<OrderSetting> findByMonth(String mm) { //2020-01
        String start = mm + "-01";
        String end = mm + "-31";
        List<OrderSetting> orderSettings = orderSettingMapper.findByMonth(start,end);
        return orderSettings;
    }

    @Override
    public void deleteByTime(String time) {
        orderSettingMapper.deleteByTime(time);
    }


}
